package cn.com.lms.business.exam.service;

import cn.com.lms.app.api.exam.dto.UserTestDTO;
import cn.com.lms.business.exam.persistence.entity.EmployeePaper;
import cn.com.lms.business.exam.persistence.entity.EmployeePaperStage;
import cn.com.lms.business.exam.persistence.repository.EmployeePaperRepository;
import cn.com.lms.business.learning.persistence.repository.LearningStageDetailRepository;
import com.bnzj.core.persistence.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Time;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;


@Service
public class EmployeePaperService extends BaseService<EmployeePaperRepository, EmployeePaper, Long> {

    @Autowired
    EmployeePaperStageService employeePaperStageService;

    @Autowired
    LearningStageDetailRepository learningStageDetailRepository;

    @Transactional(rollbackFor = Exception.class)
    public EmployeePaper saveStageEmployeePaper(UserTestDTO userTestDTO) {
        EmployeePaper employeePaper = new EmployeePaper();
        employeePaper.setCreateTime(new Date());
        employeePaper.setEmployeeId(userTestDTO.getUserId());
        employeePaper.setGrade(0);
        employeePaper.setType(Short.valueOf("1"));
        employeePaper.setRemainTime(userTestDTO.getPaperTime() * 60);
        employeePaper.setAdoptScore(userTestDTO.getAdoptScore());
        employeePaper.setLimitNum(userTestDTO.getLimitNum());
        employeePaper.setIsHand(false);
        employeePaper.setModifyTime(new Date());
        employeePaper.setPaperId(userTestDTO.getPaperId());
        EmployeePaper result = super.save(employeePaper);

        EmployeePaperStage employeePaperStage = new EmployeePaperStage();
        employeePaperStage.setStageDetailId(userTestDTO.getStageDetailId());
        employeePaperStage.setEmployeeId(userTestDTO.getUserId());
        employeePaperStage.setPaperId(userTestDTO.getPaperId());
        employeePaperStage.setEmployeePaperId(result.getId());
        employeePaperStageService.save(employeePaperStage);


        // 更新上次学习时间
        learningStageDetailRepository.updateUserLastStudyTime(userTestDTO.getStageDetailId(), userTestDTO.getUserId());
        return result;
    }
}
